package com.yifi.common;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.quartz.CronExpression;
import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerFactory;
import org.quartz.SchedulerMetaData;
import org.quartz.TriggerBuilder;
import org.quartz.TriggerKey;
import org.quartz.TriggerUtils;
import org.quartz.impl.StdSchedulerFactory;
import org.quartz.spi.OperableTrigger;

import com.jfinal.plugin.activerecord.Record;
import com.yifi.service.CronJob;


//定时任务管理类 
public class CronUtil {
	
	
	private static SchedulerFactory sf = new StdSchedulerFactory();  
    private static Class cls = CronJob.class;  
    /** 
     * @Description: 查找一个定时任务
     *  
     */  
    public static void createJob(List<Record> listCron,String jobNameF,String jobCronF,String jobGroup) {  
    	 try {  
 			Scheduler sched = sf.getScheduler();
 			for(Record r:listCron)
 			{
 				String cron = DBHelper.GetString(r, jobCronF);
 				if(!cron.equals("") )
 				{
 					String jobName = DBHelper.GetString(r, jobNameF);
 		 			JobDetail job = JobBuilder.newJob(cls).withIdentity(jobName, jobGroup).build();
 		 			CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(jobName, jobGroup).withSchedule(CronScheduleBuilder.cronSchedule(cron)).build();
 		 			sched.scheduleJob(job, trigger);
 				}
 			}
 			 // 启动  
             if (!sched.isShutdown()) {  
                 sched.start();  
             }  
         } catch (Exception e) {  
             throw new RuntimeException(e);  
         }  
    }  
    /** 
     * @Description: 查找一个定时任务
     *  
     */  
    public static boolean selectJob(String jobName,String jobGroup) {  
        try {  
            Scheduler sched = sf.getScheduler();  
            TriggerKey triggerKey = TriggerKey.triggerKey(jobName,jobGroup);
            CronTrigger trigger = (CronTrigger) sched.getTrigger(triggerKey);  
            if (trigger == null) {  
                return false;  
            }  
        } catch (Exception e) {  
            throw new RuntimeException(e);  
        }  
        return true;
    }  
    /** 
     * @Description: 添加一个定时任务
     */  
    public static void addJob(String jobName,String jobGroup, String cron) {  
        try {  
			Scheduler sched = sf.getScheduler();

			JobDetail job = JobBuilder.newJob(cls).withIdentity(jobName, jobGroup).build();
			CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(jobName, jobGroup).withSchedule(CronScheduleBuilder.cronSchedule(cron)).build();
			sched.scheduleJob(job, trigger);
			 // 启动  
            if (!sched.isShutdown()) {  
                sched.start();  
            }  
        } catch (Exception e) {  
            throw new RuntimeException(e);  
        }  
    }  
  
  
    /** 
     * @Description: 修改一个任务的触发时间
     *  
     */  
    public static void modifyJob(String jobName,String jobGroup, String cron) {  
        try {  
            Scheduler sched = sf.getScheduler();  
            TriggerKey triggerKey = TriggerKey.triggerKey(jobName,jobGroup);
            CronTrigger trigger = (CronTrigger) sched.getTrigger(triggerKey);  
            if (trigger == null) {  
                return;  
            }  
            String oldCron = trigger.getCronExpression();  
            if (!oldCron.equalsIgnoreCase(cron)) {  
            	/*JobDetail jobDetail = sched.getJobDetail(JobKey.jobKey(jobName,jobGroup));  
                Class objJobClass = jobDetail.getJobClass();  */
            	
                /*//先删除后添加
                removeJob(jobName);  
                addJob(jobName, jobGroup ,  cron);  */
            	
                // 修改时间  
                CronTrigger trigger_new = TriggerBuilder.newTrigger().withIdentity(triggerKey).withSchedule(CronScheduleBuilder.cronSchedule(cron)).build();
                //按新的trigger重新设置job执行
                sched.rescheduleJob(triggerKey, trigger_new);
                
            }  
        } catch (Exception e) {  
            throw new RuntimeException(e);  
        }  
    }  
  
 
  
    /** 
     * @Description: 移除一个任务
     */  
    public static void removeJob(String jobName,String jobGroup) {  
        try {  
            Scheduler sched = sf.getScheduler();  
            TriggerKey triggerKey = TriggerKey.triggerKey(jobName,jobGroup);
            sched.pauseTrigger(triggerKey);// 停止触发器  
            sched.unscheduleJob(triggerKey);// 移除触发器  
            JobKey jobKey = JobKey.jobKey(jobName,jobGroup);
            sched.deleteJob(jobKey);// 删除任务  
        } catch (Exception e) {  
            throw new RuntimeException(e);  
        }  
    }  
  
    /** 
     * @Description:启动所有定时任务 
     */  
    public static void startJobs() {  
        try {  
            Scheduler sched = sf.getScheduler();    
            sched.start();  
        } catch (Exception e) {  
            throw new RuntimeException(e);  
        }  
    }  
  
    /** 
     * @Description:关闭所有定时任务 
     */  
    public static void shutdownJobs() {  
        try {  
            Scheduler sched = sf.getScheduler();  
            if (sched.isStarted()) {  
                sched.shutdown();  
            }  
        } catch (Exception e) {  
            throw new RuntimeException(e);  
        }  
    }  
    

    /** 
     * @Description:获取表达式未来几次的执行时间
     */  
    public static List<String> getJobFireTime(String cron,int num) {  

		CronTrigger trigger = TriggerBuilder.newTrigger().withSchedule(CronScheduleBuilder.cronSchedule(cron)).build();
        List<Date> dates = TriggerUtils.computeFireTimes((OperableTrigger) trigger, null, num);
        
        List<String> str_dates = new ArrayList<String>();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
        for(Date d : dates){  
        	str_dates.add(dateFormat.format(d));  
        }  
        return str_dates;
    }
}
